package com.example.onlinemusicserver.service;

import cn.hutool.core.util.RandomUtil;
import com.example.onlinemusicserver.mapper.UserMapper;
import com.example.onlinemusicserver.model.User;
import com.example.onlinemusicserver.tools.RegexUtils;
import com.example.onlinemusicserver.tools.ResponseBodyMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import java.util.concurrent.TimeUnit;

import static com.example.onlinemusicserver.tools.Constant.LOGIN_CODE_KEY;
import static com.example.onlinemusicserver.tools.Constant.LOGIN_CODE_TTL;

@Slf4j
@Service
public class UserService {
    @Autowired
    public UserMapper userMapper;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    public User selectByName(String username) {
        return userMapper.selectByName(username);
    }

    public int addnewUser(User newUser) {
        return userMapper.addnewUser(newUser);
    }

    public ResponseBodyMessage<Boolean> sendCode(String phone, HttpSession session) {
        //1. 校验手机号
        if(RegexUtils.isPhoneInvalid(phone)){
            //2. 如果不符合,返回错误信息
            return new ResponseBodyMessage<>(-1,"手机号格式有问题!!",false);
        }
        //3. 符合,生成验证码
        String code = RandomUtil.randomNumbers(6);
        //4. 保存验证码到 redis
        stringRedisTemplate.opsForValue().set(LOGIN_CODE_KEY+phone,code,LOGIN_CODE_TTL, TimeUnit.MINUTES);
        //5. 发送验证码
        log.info("发送短信验证码成功,验证码{}",code);
        System.out.println("code"+code);

        return new ResponseBodyMessage<>(1,"验证码发送成功!",true);
    }
}
